package com.atom.common.activiti;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.atom.common.dao.HistoricTaskUrlDao;
import com.atom.common.entity.HistoricTaskUrlDO;
import com.atom.common.exception.AvensFileException;
import com.atom.common.remote.file.RemoteFileCommand;
import com.atom.common.remote.file.RemoteFileDao;
import com.atom.common.util.CommonHtmlGenerateUtil;
/**
 * Title: HistoricTaskDetailHandler
 * Description: 生成已办静态HTML
 * @author WEWE
 * @date 2016年6月29日 下午2:27:50
 * @version 1.0
 */
@Component
public class HistoricTaskDetailHandler {
  
  private static Logger logger = Logger.getLogger(HistoricTaskDetailHandler.class);

  @Resource HistoricTaskUrlDao historicTaskUrlDao;
  @Resource RemoteFileCommand command;
  @Resource RemoteFileDao remoteFileDao;

  public void save(Map<String, Object> map, String taskId, String templateName) {    
    try {
      String htmlUrl = CommonHtmlGenerateUtil.generate(map, templateName, taskId);
      String key = command.uploadFileByJar(htmlUrl);
      if (key != null) {
        HistoricTaskUrlDO entity = new HistoricTaskUrlDO();
        entity.setTaskId(taskId);
        entity.setHtmlUrl(key);
        historicTaskUrlDao.save(entity);
      }      
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
    }    
  }

  public File getHistory(String taskId) {
    List<HistoricTaskUrlDO> fileList = historicTaskUrlDao.findByProperty("taskId", taskId);
    if (fileList == null || fileList.size()!= 1) {
      throw new AvensFileException("Find file key by taskId failed where taskId = " + taskId);
    }

    String url = fileList.get(0).getHtmlUrl();
    String filePath = command.downloadFileByJar(url);
    File file = new File(filePath);
    if (file.exists()) {
      return file;
    }
    return null;
  }

}
